<script setup lang="ts">
import {ElMessage} from "element-plus";

defineOptions({name:'Attr'})
import useCategoryStore from '@/store/modules/category.ts'
import {reqAttr,reqAddOrUpdateAttr,reqRemoveAttr} from '@/api/product/attr/index.ts'
import {watch, ref, reactive, nextTick,onBeforeUnmount} from "vue";
import type {AttrResponseData,Attr,AttrValue} from '@/api/product/attr/type.ts'
const categoryStore = useCategoryStore()
// 存储已有的属性与属性值
const attrArr = ref<Attr[]>()
//场景切换变量
const scene =ref<number>(0)
/**
 * 根据三级分类ID获取数据
 */
const getAttr = async ()=>{
  const res:AttrResponseData = await reqAttr(categoryStore.c1Id,categoryStore.c2Id,categoryStore.c3Id)
  if(res.code==200){
    attrArr.value=res.data
  }
}
//监听仓库三级分类ID变化
watch(()=>categoryStore.c3Id, ()=>{
  attrArr.value=[]
  if(!categoryStore.c3Id) return
  getAttr()
})
/**
 * 改变场景
 */
const addAttr = () => {
  Object.assign(attrParams,{
    attrName: '',
    categoryId: '',
    categoryLevel: 3,
    attrValueList:[]
  })
  scene.value=1
  attrParams.categoryId=categoryStore.c3Id
}
/**
 * 改变场景
 */
const updateAttr = (row:Attr) => {
  scene.value=1
  Object.assign(attrParams,JSON.parse(JSON.stringify(row)))
}
/**
 * 取消新增
 */
const cancel = () => {
  scene.value=0
}
//添加或修改的对象映射
const attrParams = reactive<Attr>({
  attrName: '',
  categoryId: '',
  categoryLevel: 3,
  attrValueList:[]
})
/**
 *添加属性值
 */
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName:'',
    flag:true
  })
  nextTick(()=>{
    inputArr.value[attrParams.attrValueList.length-1].focus()
  })
}
/**
 * 保存属性，发送请求
 */
const save = async () => {
  const res = await reqAddOrUpdateAttr(attrParams)
  // console.log(res)
  if(res.code==200){
    scene.value=0
    await getAttr()
    ElMessage({
      type:'success',
      message:attrParams.id?'修改成功':'添加成功'
    })
  }else{
    ElMessage({
      type:'success',
      message:attrParams.id?'修改失败':'添加失败'
    })
  }
}
/**
 * 属性值表单元素失去焦点的方法
 */
const toLook = (row:AttrValue,index:number) => {
  // 输入空值进行提示
  if(row.valueName.trim()==''){
    ElMessage({
      type:'error',
      message:'属性值不能为空'
    })
    //从数组中移除掉空值
    attrParams.attrValueList.splice(index)
    return;
  }
  //数组去重
  const repeat = attrParams.attrValueList.find((item)=>{
    if(item!=row){
      return item.valueName===row.valueName
    }
  })
  if(repeat){
    attrParams.attrValueList.splice(index,1)
    ElMessage({
      type:'error',
      message:'属性值不能重复'
    })
    return
  }
  row.flag=false
}
/**
 * 属性值变为编辑状态
 */
const toEdit = (row:AttrValue,index:number) => {
  row.flag=true
  nextTick(()=>{
    inputArr.value[index]?.focus()
  })
}
//input的组件实例
let inputArr = ref<any>([])
/**
 * 删除一个属性
 */
const deleteAttr = async (attrId:number) => {
  const res:any = await reqRemoveAttr(attrId)
  if(res.code==200){
    ElMessage({
      type:'success',
      message:'删除成功'
    })
    await getAttr()
  }else {
    ElMessage({
      type:'error',
      message:'删除失败'
    })
  }
}

onBeforeUnmount(()=>{
  categoryStore.$reset()
})
</script>

<template>
  <Category :scene="scene"/>
  <el-card style="margin: 10px 0">
    <div v-show="scene==0">
      <el-button type="primary" icon="Plus" :disabled="!categoryStore.c3Id" @click="addAttr">添加属性</el-button>
      <el-table border style="margin: 10px 0" :data="attrArr">
        <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
        <el-table-column label="属性名称" width="120px" prop="attrName"></el-table-column>
        <el-table-column label="属性值名称" prop="">
          <template #default="{row}">
            <el-tag v-for="item in row.attrValueList" :key="item.id" style="margin: 0 5px;">
              {{item.valueName}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template #default="{row}">
            <el-button type="warning" icon="Edit" @click="updateAttr(row)"></el-button>
            <el-popconfirm :title="`你确定删除${row.attrName}`"
                           confirm-button-text="确定"
                           cancel-button-text="取消"
                           @confirm="deleteAttr(row.id)"
                           width="200px">
              <template #reference>
                <el-button type="danger" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="scene==1">
      <el-form :inline="true">
        <el-form-item label="属性名称">
          <el-input placeholder="请你输入属性名称" v-model="attrParams.attrName"></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" :disabled="!attrParams.attrName" @click="addAttrValue">添加属性</el-button>
      <el-button type="primary" @click="cancel">取消</el-button>
      <el-table border style="margin: 10px 0;" :data="attrParams.attrValueList">
        <el-table-column width="80px" type="index" align="center" label="序号"></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{row,$index}">
            <el-input placeholder="请你输入属性值名称"
                      @blur="toLook(row,$index)"
                      v-model="row.valueName"
                      v-if="row.flag"
                      size="small"
                      :ref="(vc:any)=>inputArr[$index]=vc"
            />
            <div @click="toEdit(row,$index)" v-else>{{row.valueName}}</div>
          </template>
        </el-table-column>
        <el-table-column label="属性值操作">
          <template #default="{index}">
            <el-button type="primary" size="small" icon="Delete" @click="attrParams.attrValueList.splice(index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="save" :disabled="!(attrParams.attrValueList.length>0)">保存</el-button>
      <el-button type="primary" @click="cancel">取消</el-button>
    </div>
  </el-card>
</template>

<style scoped lang="scss">
</style>